#Function to read in quality files

readQualFiles <- function(qual.reads,location){
	#input a vector containing read names
	#a directory where qual files are
	
	if(any(nchar(qual.reads)>14)) qual.reads <- substr(qual.reads,1,14)
	plates <- unique(substr(qual.reads,1,9))
	plate.files <- paste(location,"/",plates,".qual",sep="")
	qual.res <- list()
	tmp.ids <- paste(location,"/","tmp.ids",sep="")
	
	for(i in 1:length(plate.files)){
		cat(paste(qual.reads[grep(plates[i],qual.reads)],"\n",sep=""),
		file=tmp.ids,sep="")
		tmp.cmd <- paste("perl /Paterson/Datafiles/grouse/grouse_analysis/getQualFasta.pl",
			plate.files[i], tmp.ids)
		
		qual.res[[i]] <- system(tmp.cmd,intern=TRUE)
		}
	names(qual.res) <- plates
	qual.res
	}

extractQual <- function(qual.res){
	#manipulate output from readQualFiles
	qual.str.vec <- unlist(qual.res)
	header.lines <- grep('>',qual.str.vec)
	read.qual.names <- substr(qual.str.vec[header.lines],2,15)
	read.starts <- header.lines+1
	
	if(length(read.starts)==1){
		read.stops <- length(qual.str.vec)
		}else{
		read.stops <- c(header.lines[2:length(header.lines)]-1,length(qual.str.vec))
		}
	qual.df <- data.frame(str=qual.str.vec,stringsAsFactors=FALSE)
	qual.df$read <- factor(x=rep(read.qual.names,times=read.stops-header.lines+1),levels=read.qual.names)
	
	qual.reads <- by(data=qual.df,
	INDICES=qual.df$read,
	FUN=function(data){
		tmp.str <- paste(data$str[-1],collapse=" ")
		as.numeric(strsplit(tmp.str,' ')[[1]])
		},simplify=FALSE) 
	names(qual.reads) <- read.qual.names
	qual.reads
	#output is a by object, essentially a list
	}

